/*
 * FrmGeraBoletoBlocoBB.java
 *
 * Created on 12 de Novembro de 2008, 18:37
 */
package org.jboleto.view;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Random;
import java.util.Vector;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.events.StartDocument;
import javax.xml.stream.events.StartElement;
import javax.xml.stream.events.XMLEvent;
import org.jboleto.JBoleto;
import org.jboleto.JBoletoBean;
import org.jboleto.control.Generator;
import org.jboleto.control.PDFGenerator;

/**
 *
 * @author  wanderson
 */
public class FrmGeraBoletoBlocoCAIXA extends javax.swing.JFrame {

    String data[][] = {{"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", ""}};
    String col[] = {"Nosso Núm.", "Sacado", "Endereço", "Bairro", "Cidade", "UF", "CEP", "CPF", "Valor", "Código da operação", "Carteira", "Código Fornecido Agência", "DV Código Fornecido Agência", "Vencimento","Mensagem personalizada 1","Mensagem personalizada 2"};
    DefaultTableModel model = new DefaultTableModel(data, col);
    String dataHead[][] = {{"", "", "", "", ""}};
    String colHead[] = {"Agência.", "Conta Corrente", "Dígito verificador", "Data Documento", "Cedente"};
    DefaultTableModel modelHead = new DefaultTableModel(dataHead, colHead);

    /** Creates new form FrmGeraBoletoBlocoBB */
    public FrmGeraBoletoBlocoCAIXA() {
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jBtnRecuperarXML = new javax.swing.JButton();
        jBtnEscolherArquivo = new javax.swing.JButton();
        jTxtXmlUrl = new javax.swing.JTextField();
        jBtnProcessarBoletos = new javax.swing.JButton();
        jTxtDestinoOutput = new javax.swing.JTextField();
        jBtnLocalOutput = new javax.swing.JButton();
        jPanel4 = new javax.swing.JPanel();
        jScrollPane5 = new javax.swing.JScrollPane();
        jTblBoletos = new javax.swing.JTable();
        jScrollPane6 = new javax.swing.JScrollPane();
        jTableHead = new javax.swing.JTable();
        jTxtMsg01 = new javax.swing.JTextField();
        jTxtMsg02 = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jTxtMsgFIXO = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jTxtImagemPropaganda = new javax.swing.JTextField();
        jBtnImagemPropaganda = new javax.swing.JButton();

        setTitle("Geração de Bloquetos de Cobrança em Bloco Caixa Econômica Federal convênio sem Partição...");
        setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowActivated(java.awt.event.WindowEvent evt) {
                formWindowActivated(evt);
            }
        });

        jBtnRecuperarXML.setLabel("Transferir Dados Para Tabela");
        jBtnRecuperarXML.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBtnRecuperarXMLActionPerformed(evt);
            }
        });

        jBtnEscolherArquivo.setText("Escolher Arquivo XML");
        jBtnEscolherArquivo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBtnEscolherArquivoActionPerformed(evt);
            }
        });

        jTxtXmlUrl.setEditable(false);

        jBtnProcessarBoletos.setText("Processar Boletos");
        jBtnProcessarBoletos.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBtnProcessarBoletosActionPerformed(evt);
            }
        });

        jBtnLocalOutput.setText("Escolher Destino");
        jBtnLocalOutput.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBtnLocalOutputActionPerformed(evt);
            }
        });

        jPanel4.setBorder(javax.swing.BorderFactory.createTitledBorder("Dados"));

        jTblBoletos.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jTblBoletos.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
        jScrollPane5.setViewportView(jTblBoletos);

        jTableHead.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane6.setViewportView(jTableHead);

        jLabel1.setText("Mensagem");

        jLabel2.setText("Mensagem");

        jTxtMsgFIXO.setText("REFERENTE AO EXERCICIO XXXX");

        jLabel3.setText("Mensagem");

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane5, javax.swing.GroupLayout.DEFAULT_SIZE, 428, Short.MAX_VALUE)
                    .addComponent(jScrollPane6, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 428, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jTxtMsg02, javax.swing.GroupLayout.DEFAULT_SIZE, 373, Short.MAX_VALUE))
                    .addGroup(jPanel4Layout.createSequentialGroup()
                        .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(jLabel3))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jTxtMsgFIXO, javax.swing.GroupLayout.DEFAULT_SIZE, 373, Short.MAX_VALUE)
                            .addComponent(jTxtMsg01, javax.swing.GroupLayout.DEFAULT_SIZE, 373, Short.MAX_VALUE))))
                .addContainerGap())
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup()
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTxtMsgFIXO, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTxtMsg01, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTxtMsg02, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane6, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane5, javax.swing.GroupLayout.PREFERRED_SIZE, 146, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        jBtnImagemPropaganda.setText("Escolher Imagem");
        jBtnImagemPropaganda.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBtnImagemPropagandaActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel4, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jBtnEscolherArquivo)
                    .addComponent(jTxtXmlUrl, javax.swing.GroupLayout.DEFAULT_SIZE, 460, Short.MAX_VALUE)
                    .addComponent(jBtnRecuperarXML)
                    .addComponent(jBtnProcessarBoletos, javax.swing.GroupLayout.PREFERRED_SIZE, 244, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(jTxtImagemPropaganda, javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jTxtDestinoOutput, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 341, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jBtnImagemPropaganda, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jBtnLocalOutput, javax.swing.GroupLayout.DEFAULT_SIZE, 113, Short.MAX_VALUE))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jBtnEscolherArquivo)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jTxtXmlUrl, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jBtnRecuperarXML)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTxtImagemPropaganda, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jBtnImagemPropaganda))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTxtDestinoOutput, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jBtnLocalOutput))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jBtnProcessarBoletos)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
    private void jBtnRecuperarXMLActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBtnRecuperarXMLActionPerformed

        final ProgressBar barra = new ProgressBar();
        JFrame frame = new JFrame("Transferindo Dados para a Tabela.... Aguarde....");
        frame.setSize(600, 70);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setContentPane(barra);
        frame.setVisible(true);
        frame.setLocation(400, 300);
        barra.atualizaBarra(1);
        
        model.setNumRows(0);
        modelHead.setNumRows(0);
        try {
            //-- Necessario para ler o Xml - Stax
            XMLInputFactory fInput = XMLInputFactory.newInstance();
            XMLStreamReader reader = fInput.createXMLStreamReader(new FileInputStream(jTxtXmlUrl.getText()));
            
            ArrayList listaItens = new ArrayList();
            StringBuilder linhas = new StringBuilder();
            
            String agencia = null;
            String contaCorrente = null;
            String dvcontacorrente = null;
            String datadocumento = null;
            String cedente = null;
            
            String msg01 = null;
            String msg02 = null;
            
            String msg03 = null;
            String msg04 = null;
            
            String nome = null;
            String endereco = null;
            String bairro = null;
            String cidade = null;
            String uf = null;
            String cep = null;
            String cpf = null;
            
            String vencimento = null;
            String nossoNumero = null;
            
            String carteira = null;
            String codOperacao = null;
            String codFornecidoAgencia = null;
            String dvCodFornecidoAgencia = null;
            
            String valor = null;
            
            int i = 1;
            while (reader.hasNext()) {
                
                final int percent = i;
                barra.atualizaBarra(percent);
                
                int evento = reader.getEventType();
                
                if (evento == XMLStreamReader.START_DOCUMENT) {
                    //System.out.println("Iniciou Documento");
                } else if (evento == XMLStreamReader.START_ELEMENT) {
                    //System.out.println("Startou Elemento");
                    String nomeTag = reader.getLocalName();
                    if ("boletos".equals(nomeTag)) {
                        agencia = reader.getAttributeValue(null, "agencia");
                        contaCorrente = reader.getAttributeValue(null, "contacorrente");
                        dvcontacorrente = reader.getAttributeValue(null, "dvcontacorrente");
                        datadocumento = reader.getAttributeValue(null, "datadocumento");
                        cedente = reader.getAttributeValue(null, "cedente");
                        msg01 = reader.getAttributeValue(null, "mensagem01");
                        msg02 = reader.getAttributeValue(null, "mensagem02");
                        System.out.println("Agencia :" + agencia + " - " + "Conta Corrente: " + contaCorrente + "-" + dvcontacorrente + " -" + "Data : " + datadocumento + " - " + cedente);
                    } else if ("NOMSAC".equals(nomeTag)) {
                        nome = reader.getElementText();
                    } else if ("ENDSAC".equals(nomeTag)) {
                        endereco = reader.getElementText();
                    } else if ("BAISAC".equals(nomeTag)) {
                        bairro = reader.getElementText();
                    } else if ("CIDSAC".equals(nomeTag)) {
                        cidade = reader.getElementText();
                    } else if ("UFESAC".equals(nomeTag)) {
                        uf = reader.getElementText();
                    } else if ("CEPSAC".equals(nomeTag)) {
                        cep = reader.getElementText();
                    } else if ("CPFSAC".equals(nomeTag)) {
                        cpf = reader.getElementText();
                    } else if ("VENCIM".equals(nomeTag)) {
                        vencimento = reader.getElementText();
                    } else if ("NOSSON".equals(nomeTag)) {
                        String NossoNcompleto = reader.getElementText();
                        carteira = NossoNcompleto.substring(0,2);
                        nossoNumero = NossoNcompleto.substring(2,10);
                    } else if ("NUMCON".equals(nomeTag)) {
                        String ConvenioCompleto = reader.getElementText();
                        codOperacao = ConvenioCompleto.substring(0, 3);
                        codFornecidoAgencia =  ConvenioCompleto.substring(3, 11);
                        dvCodFornecidoAgencia = ConvenioCompleto.substring(11, 12);
                    } else if ("CARTEI".equals(nomeTag)) {
                        //carteira = reader.getElementText();
                    } else if ("VALORB".equals(nomeTag)) {
                        valor = reader.getElementText();
                    } else if ("MSG03".equals(nomeTag)) {
                        //msg03 = reader.getElementText();
                        msg03 = "";
                    } else if ("MSG04".equals(nomeTag)) {
                        msg04 = reader.getElementText();
                    }
                } else if (evento == XMLStreamReader.END_ELEMENT) {
                    String nomeTag = reader.getLocalName();
                    if ("boleto".equals(nomeTag)) {

                        //-- {"Nosso Núm.", "Sacado", "Endereço", "Bairro", "Cidade", "UF", "CEP", "CPF", "Valor", "Código da operação", "Carteira", "Código Fornecido Agência", "DV Código Fornecido Agência", "Vencimento","Mensagem personalizada 1","Mensagem personalizada 2"}
                        model.insertRow(0, new Object[]{nossoNumero, nome, endereco, bairro, cidade, uf, cep, cpf, valor, codOperacao, carteira, codFornecidoAgencia, dvCodFornecidoAgencia, vencimento, msg03, msg04});

                        nome = null;
                        endereco = null;
                        bairro = null;
                        cidade = null;
                        uf = null;
                        cep = null;
                        cpf = null;
                        vencimento = null;
                        nossoNumero = null;
                        codFornecidoAgencia = null;
                        dvCodFornecidoAgencia = null;
                        codOperacao = null;
                        carteira = null;
                        valor = null;
                        msg03 = null;
                        msg04 = null;
                    }
                }
                evento = reader.next();
                i++;
            }
            frame.setVisible(false);
            modelHead.insertRow(0, new Object[]{agencia, contaCorrente, dvcontacorrente, datadocumento, cedente});
            jTxtMsg01.setText(msg01);
            jTxtMsg02.setText(msg02);
            modelHead.removeRow(jTableHead.getRowCount());
        } catch (Exception exception) {
            exception.getMessage();
        }
        
    //for (int i = 0; i < 10000; i++) {
    //    model.insertRow(0, new Object[]{"8200000001", "WANDERSON CAMARA DOS SANTOS", "AV. SENADOR SALGADO FILHO", "LAGOA NOVA", "NATAL", "RN", "59000000", "00000000011", "180,98", "123456", "10/02/2009"});
    //}
}//GEN-LAST:event_jBtnRecuperarXMLActionPerformed

    private void jBtnEscolherArquivoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBtnEscolherArquivoActionPerformed
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setDialogTitle("Selecione o Arquivo Xml Contendo os Dados Para Impressão dos Boletos");
        int result = fileChooser.showOpenDialog(fileChooser);


        if (result == JFileChooser.OPEN_DIALOG) {
            String file = fileChooser.getSelectedFile().getPath();
            jTxtXmlUrl.setText(file);
        }
}//GEN-LAST:event_jBtnEscolherArquivoActionPerformed

    private void formWindowActivated(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowActivated
        jTblBoletos.setModel(model);
        jTableHead.setModel(modelHead);
    }//GEN-LAST:event_formWindowActivated

    private void jBtnProcessarBoletosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBtnProcessarBoletosActionPerformed

        try {
            
            final ProgressBar barra = new ProgressBar();
            JFrame frame = new JFrame("Gerando Boletos.... Aguarde....");
            frame.setSize(400, 70);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setContentPane(barra);
            frame.setVisible(true);
            frame.setLocation(400, 300);
            
            barra.atualizaBarra(20);
            
            JBoletoBean jBoletoBean = new JBoletoBean();
            
            jBoletoBean.setDataDocumento("23/10/2008");
            jBoletoBean.setDataProcessamento("23/10/2008");
            
            jBoletoBean.setCedente("CEDENTE TESTE");
            
            jBoletoBean.setNomeSacado("SACADO TESTE");
            jBoletoBean.setEnderecoSacado("Av. Teste");
            jBoletoBean.setBairroSacado("Bairro teste");
            jBoletoBean.setCidadeSacado("Estado teste");
            jBoletoBean.setUfSacado("XX");
            jBoletoBean.setCepSacado("59040-580");
            jBoletoBean.setCpfSacado("0000000000000");

            //jBoletoBean.setLocalPagamento("QUALQUER AGENCIA BANCÁRIA ATÉ O VENCIMENTO");
            //jBoletoBean.setLocalPagamento2("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
            Vector descricoes = new Vector();
            jBoletoBean.setDescricoes(descricoes);

            jBoletoBean.setDescricoes(descricoes);
            if((!jTxtImagemPropaganda.getText().isEmpty())){
                jBoletoBean.setImagemMarketing(jTxtImagemPropaganda.getText());
            }

            jBoletoBean.setDataVencimento("23/10/2008");
            jBoletoBean.setInstrucao1("");
            jBoletoBean.setInstrucao2("");
            jBoletoBean.setInstrucao3("");
            jBoletoBean.setInstrucao4("");
            
            jBoletoBean.setAgencia("0000");
            jBoletoBean.setContaCorrente("00000000"); //completar com zeros quando necessario
            jBoletoBean.setDvContaCorrente("X");
            
            jBoletoBean.setCarteira("82");
            jBoletoBean.setCodigoOperacao("870");
            jBoletoBean.setCodigoFornecidoAgencia("00000324");
            jBoletoBean.setDvCodigoFornecidoAgencia("02");
            
            jBoletoBean.setNossoNumero("19525086",8);
            jBoletoBean.setNoDocumento("987656123");

            jBoletoBean.setValorBoleto("2952.95");
            jBoletoBean.setDataVencimento("02/10/2007");

            Generator generator = new PDFGenerator(jBoletoBean, JBoleto.CAIXA_ECONOMICA);
            JBoleto jBoleto = new JBoleto(generator, jBoletoBean, JBoleto.CAIXA_ECONOMICA);
            
            for (int i = 0; i < jTblBoletos.getRowCount(); i++) {
                
                final int percent = i;
                barra.atualizaBarra(percent);
                
                //System.out.println(i);
                
                //-- "Agência.","Conta Corrente", "Dígito verificador", "Data Documento", "Cedente"
                //-- {"Nosso Núm.", "Sacado", "Endereço", "Bairro", "Cidade", "UF", "CEP", "CPF", "Valor", "Código da operação", "Carteira", "Código Fornecido Agência", "DV Código Fornecido Agência", "Vencimento","Mensagem personalizada 1","Mensagem personalizada 2"}
                
                jBoletoBean.setDataDocumento(jTableHead.getValueAt(0, 3).toString());
                jBoletoBean.setDataProcessamento(jTableHead.getValueAt(0, 3).toString());
                
                jBoletoBean.setCedente(jTableHead.getValueAt(0, 4).toString());
                
                jBoletoBean.setNomeSacado(jTblBoletos.getValueAt(i, 1).toString());
                jBoletoBean.setEnderecoSacado(jTblBoletos.getValueAt(i, 2).toString());
                jBoletoBean.setBairroSacado(jTblBoletos.getValueAt(i, 3).toString());
                jBoletoBean.setCidadeSacado(jTblBoletos.getValueAt(i, 4).toString());
                jBoletoBean.setUfSacado(jTblBoletos.getValueAt(i, 5).toString());
                jBoletoBean.setCepSacado(jTblBoletos.getValueAt(i, 6).toString());
                jBoletoBean.setCpfSacado(jTblBoletos.getValueAt(i, 7).toString());
                
                jBoletoBean.setLocalPagamento("QUALQUER AGENCIA BANCÁRIA ATÉ O VENCIMENTO");
                
                if((!jTxtImagemPropaganda.getText().isEmpty())){
                    jBoletoBean.setImagemMarketing(jTxtImagemPropaganda.getText());
                }
                
                jBoletoBean.setDataVencimento(jTblBoletos.getValueAt(i, 13).toString());
                jBoletoBean.setInstrucao4(jTxtMsg01.getText());
                jBoletoBean.setInstrucao5(jTxtMsg02.getText());
                
                jBoletoBean.setInstrucao1(jTxtMsgFIXO.getText());
                jBoletoBean.setInstrucao2(jTblBoletos.getValueAt(i, 14).toString());
                
                jBoletoBean.setInstrucao3(jTblBoletos.getValueAt(i, 15).toString());
                
                jBoletoBean.setAgencia(jTableHead.getValueAt(0, 0).toString());
                jBoletoBean.setContaCorrente(jTableHead.getValueAt(0, 1).toString()); //completar com zeros quando necessario
                jBoletoBean.setDvContaCorrente(jTableHead.getValueAt(0, 2).toString());
                
                jBoletoBean.setCarteira( jTblBoletos.getValueAt(i, 10).toString() );
                jBoletoBean.setCodigoOperacao( jTblBoletos.getValueAt(i, 9).toString() );
                jBoletoBean.setCodigoFornecidoAgencia( jTblBoletos.getValueAt(i, 11).toString() );
                jBoletoBean.setDvCodigoFornecidoAgencia( jTblBoletos.getValueAt(i, 12).toString() );
                //-- jBoletoBean.setDvCodigoFornecidoAgencia( "02" );
                jBoletoBean.setNoDocumento( jTblBoletos.getValueAt(i, 10).toString()+jTblBoletos.getValueAt(i, 0).toString() );
                jBoletoBean.setNossoNumero(jTblBoletos.getValueAt(i, 0).toString(), 8);
                jBoletoBean.setValorBoleto(jTblBoletos.getValueAt(i, 8).toString());
                
                jBoleto.addBoleto();
                
            }
            jBoleto.closeBoleto(jTxtDestinoOutput.getText() + "/" + "BoletosMinervaJAVA" + ".pdf");
            frame.setVisible(false);
            JOptionPane.showMessageDialog(null, "Arquivo com Boleto Gerado com Sucesso!");
        } catch (Exception exception) {
            exception.getMessage();
        }
        
    }//GEN-LAST:event_jBtnProcessarBoletosActionPerformed

    private void jBtnLocalOutputActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBtnLocalOutputActionPerformed
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        fileChooser.setDialogTitle("Selecione o diretório de destino do arquivo PDF contendo os Boletos");
        int result = fileChooser.showOpenDialog(fileChooser);

        if (result == JFileChooser.OPEN_DIALOG) {
            File file = fileChooser.getSelectedFile();
            jTxtDestinoOutput.setText(file.getPath());
        }
    }//GEN-LAST:event_jBtnLocalOutputActionPerformed

    private void jBtnImagemPropagandaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBtnImagemPropagandaActionPerformed
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setDialogTitle("Selecione o Arquivo de Imagem contendo o Marketing a ser Impresso no(s) Boleto(s)");
        int result = fileChooser.showOpenDialog(fileChooser);


        if (result == JFileChooser.OPEN_DIALOG) {
            String file = fileChooser.getSelectedFile().getPath();
            jTxtImagemPropaganda.setText(file);
        }
    }//GEN-LAST:event_jBtnImagemPropagandaActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new FrmGeraBoletoBlocoCAIXA().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jBtnEscolherArquivo;
    private javax.swing.JButton jBtnImagemPropaganda;
    private javax.swing.JButton jBtnLocalOutput;
    private javax.swing.JButton jBtnProcessarBoletos;
    private javax.swing.JButton jBtnRecuperarXML;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JScrollPane jScrollPane5;
    private javax.swing.JScrollPane jScrollPane6;
    private javax.swing.JTable jTableHead;
    private javax.swing.JTable jTblBoletos;
    private javax.swing.JTextField jTxtDestinoOutput;
    private javax.swing.JTextField jTxtImagemPropaganda;
    private javax.swing.JTextField jTxtMsg01;
    private javax.swing.JTextField jTxtMsg02;
    private javax.swing.JTextField jTxtMsgFIXO;
    private javax.swing.JTextField jTxtXmlUrl;
    // End of variables declaration//GEN-END:variables
}
